package com.ee.chat.admin.service.impl;

import com.ee.chat.admin.service.IIndexService;
import com.ee.chat.common.bean.MenuTree;
import com.ee.chat.common.dao.AdminMenuMapper;
import com.ee.chat.common.dao.AdminUserMapper;
import com.ee.chat.common.entity.AdminUser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Author Shane
 * @Date 2019/7/16 23:37
 */
@Service
public class IndexServiceImpl implements IIndexService {
    @Resource
    AdminUserMapper adminUserMapper;
    @Resource
    AdminMenuMapper adminMenuMapper;

    @Override
    public List<MenuTree> getUserMenuTrees(HttpSession session) {
        AdminUser adminUser = (AdminUser)session.getAttribute("adminUser");
        Integer userId = adminUser.getId();

        return getUserMenu(userId);
    }

    @Override
    public List<String> getUserPermissions(Integer userId) {
        return adminUserMapper.getUserPermissionUrls(userId);
    }

    @Override
    public List<MenuTree> getUserMenu(Integer userId) {
        List<Integer> ids;
        AdminUser adminUser = adminUserMapper.selectById(userId);
        if(adminUser.getSystem() == 1){ //系统内置超级管理员，拥有全部权限
            ids = adminUserMapper.getUserMenuIds(null);
        }else{
            ids = adminUserMapper.getUserMenuIds(userId);
        }
        List<MenuTree> trees = adminUserMapper.getMenuTreeByPid(0, 0);
        handleUserMenu(trees, ids);
        return trees;
    }

    @Override
    public void handleUserMenu(List<MenuTree> trees, List<Integer> ids) {
        Iterator<MenuTree> it = trees.iterator();
        while (it.hasNext()){
            MenuTree tree = it.next();
            List<MenuTree> childrens = new ArrayList<>();
            if(ids.contains(tree.getId())){
                childrens = adminUserMapper.getMenuTreeByPid(tree.getId(), null);
                handleUserMenu(childrens, ids);
            }else{
                it.remove();
            }
            tree.setChildrens(childrens);
        }
    }

    @Override
    public List<MenuTree> getMenuPermission() {
        List<MenuTree> trees = adminUserMapper.getMenuTreeByPid(0, null);
        List<Integer> ids = adminMenuMapper.getMenuPermissionIds();
        handleUserMenu(trees, ids);
        return trees;
    }
}
